﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JewererBasic.Models;
using JewererBasic.BO;
using JewererBasic.Classes;

namespace JewererBasic.Controllers
{
    public class StoneController : Controller
    {
        private MSQDBEntities db = new MSQDBEntities();

        private List<TYPE> listTypes;
        private List<UNIT> listUnits;

        #region Index Home
        public ActionResult Index()
        {
            ImportedStones.Clear();
            BagStones.Clear();
            TestingStones.Clear();

            listTypes = new List<TYPE>(db.TYPEs.ToList());
            listUnits = new List<UNIT>(db.UNITs.ToList());

            ViewBag.Types = listTypes;
            ViewBag.Units = listUnits;

            return View(db.STONEs.ToList());
        }

        [HttpPost]
        public ActionResult Index(FormCollection fc)
        {
            ImportedStones.Clear();
            BagStones.Clear();
            TestingStones.Clear();

            listTypes = new List<TYPE>(db.TYPEs.ToList());
            listUnits = new List<UNIT>(db.UNITs.ToList());

            ViewBag.Types = listTypes;
            ViewBag.Units = listUnits;

            string id = fc["txtId"];
            string name = fc["txtName"];
            string description = fc["txtDescription"];
            string typeId = fc["ddlType"];
            string unitId = fc["ddlUnit"];
            string weight = fc["txtWeight"];
            string quantity = fc["txtQuantity"];

            if (fc["submit"] == "ADD")
            {
                if (String.IsNullOrEmpty(id) || String.IsNullOrEmpty(name)
                    || String.IsNullOrEmpty(typeId) || String.IsNullOrEmpty(unitId))
                {
                    return View(db.STONEs.ToList());
                }
                else
                {
                    try
                    {
                        STONE stone = new STONE();
                        stone.Id = id;
                        stone.Name = name;
                        stone.Decription = description;
                        stone.IdType = Int32.Parse(typeId);
                        stone.IdUnit = Int32.Parse(unitId);
                        stone.Weight = Double.Parse(weight);
                        stone.Numb = Int32.Parse(quantity);
                        stone.DayMake = DateTime.Now;
                        stone.IdCreater = CurrentUser.UserID;

                        StoneBO.Add(stone);
                    }
                    catch (Exception e)
                    {
                        return View(db.STONEs.ToList());
                    }
                }
            }
            else if (fc["submit"] == "SEARCH")
            {
                string searchId = fc["txtSearchId"];
                string searchName = fc["txtSearchName"];
                return View(StoneBO.Search(searchId, searchName));
            }
            else if (fc["submit"] == "IMPORT")
            {
                return RedirectToAction("Import");
            }
            else if (fc["submit"] == "STAFF EXP")
            {
                return RedirectToAction("TestingExport");
            }
            else if (fc["submit"] == "BAG EXP")
            {
                return RedirectToAction("BagExport");
            }
            else if (fc["submit"] == "HISTORY")
            {
                ClearSearchHistory();
                return RedirectToAction("History");
            }

            return View(db.STONEs.ToList());
        }

        public ActionResult AddStone(string id, string name, string description, int typeId, int unitId, float weight, int quantity)
        {
            bool result = true;

            STONE s = new STONE();
            s.Id = id;
            s.Name = name;
            s.Decription = description;
            s.IdType = typeId;
            s.IdUnit = unitId;
            s.Weight = weight;
            s.Numb = quantity;
            s.DayMake = DateTime.Now;
            s.IdCreater = CurrentUser.UserID;

            result = StoneBO.Add(s);

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region Import
        private static List<ServiceStone> ImportedStones = new List<ServiceStone>();
        public ActionResult Import()
        {
            ViewBag.CurrentUser = CurrentUser.UserID;
            ViewBag.CurrentDate = DateTime.Now.Date.ToShortDateString();

            return View(ImportedStones);
        }

        //[HttpPost]
        //public ActionResult Import(FormCollection fc)
        //{
        //    ViewBag.CurrentUser = CurrentUser.UserID;
        //    ViewBag.CurrentDate = DateTime.Now.Date.ToShortDateString();

        //    string id = fc["txtId"];
        //    string weight = fc["txtWeight"];
        //    string quantity = fc["txtQuantity"];

        //    STONE_IMPORT si = new STONE_IMPORT();
        //    List<STONE_IMPORT_DETAIL> listSid = new List<STONE_IMPORT_DETAIL>();
        //    foreach (var item in ImportedStones)
        //    {
        //        STONE_IMPORT_DETAIL sid = new STONE_IMPORT_DETAIL();
        //        sid.IdStone = item.Id;
        //        sid.Weight = item.Weight;
        //        sid.Numb = item.Quantity;
        //        listSid.Add(sid);
        //    }

        //    StoneBO.Import(si, listSid);
        //    ImportedStones.Clear();

        //    return RedirectToAction("Index");
        //}

        public JsonResult SaveImport()
        {
            STONE_IMPORT si = new STONE_IMPORT();
            List<STONE_IMPORT_DETAIL> listSid = new List<STONE_IMPORT_DETAIL>();
            foreach (var item in ImportedStones)
            {
                STONE_IMPORT_DETAIL sid = new STONE_IMPORT_DETAIL();
                sid.IdStone = item.Id;
                sid.Weight = item.Weight;
                sid.Numb = item.Quantity;
                sid.Reason = item.Reason;
                listSid.Add(sid);
            }

            StoneBO.Import(si, listSid);
            ImportedStones.Clear();

            return Json(new { id = si.Id }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region Testing Export
        public ActionResult TestingExportList()
        {
            return View(this.db.STONE_EXPORTSTAFF.ToList());
        }

        public ActionResult TestingExportUpdate(int id)
        {
            STONE_EXPORTSTAFF se = this.db.STONE_EXPORTSTAFF.Find(id);
            if (se == null)
            {
                return RedirectToAction("TestingExportList");
            }

            if (se.IsFinish == 1) // finish
            {
                return RedirectToAction("TestingExportDetail", new { id = se.IdExport });
            }

            List<STONE_EXPORTSTAFFDETAIL> list = se.STONE_EXPORTSTAFFDETAIL.ToList();
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    item.ReturnQuantity = 0;
                    item.ReturnWeight = 0;
                }
            }

            ViewBag.ExportId = se.IdExport;

            return View(list);
        }

        [HttpPost]
        public ActionResult TestingExportUpdate(IEnumerable<STONE_EXPORTSTAFFDETAIL> model, FormCollection fc)
        {
            string exportId = fc["exportId"];
            int id;
            if (Int32.TryParse(exportId, out id) == false)
            {
                return RedirectToAction("TestingExportList");
            }

            STONE_EXPORTSTAFF se = this.db.STONE_EXPORTSTAFF.Find(id);
            if (se == null)
            {
                return RedirectToAction("TestingExportList");
            }
            else
            {
                if (fc["submit"] == "Save")
                {
                    se.IsFinish = -1;
                }
                else if (fc["submit"] == "Finish")
                {
                    se.IsFinish = 1;
                }

                var query = from d in db.STONE_EXPORTSTAFFDETAIL
                            where d.IdExport == se.IdExport
                            select d;
                if (query.Count() > 0)
                {
                    foreach (var item in query)
                    {
                        STONE_EXPORTSTAFFDETAIL sesd = model.Where(m => m.IdStone == item.IdStone).First();
                        if (sesd != null)
                        {
                            item.ReturnWeight += sesd.ReturnWeight;
                            item.ReturnWeight = Math.Round(item.ReturnWeight, 3);
                            item.ReturnQuantity += sesd.ReturnQuantity;
                            // cong weight, quantity trong stone
                            STONE s = this.db.STONEs.Find(item.IdStone);
                            if (s != null)
                            {
                                s.Weight += sesd.ReturnWeight;
                                if (s.Weight.HasValue)
                                {
                                    s.Weight = Math.Round(s.Weight.Value, 3);
                                }
                                s.Numb += sesd.ReturnQuantity;
                            }
                        }
                    }
                }

                db.SaveChanges();

                return View("TestingExportDetail", se);
            }
        }

        public ActionResult TestingExportDetail(int id)
        {
            STONE_EXPORTSTAFF se = this.db.STONE_EXPORTSTAFF.Find(id);
            if (se == null)
            {
                return RedirectToAction("TestingExportList");
            }

            return View(se);
        }

        private static List<ServiceStone> TestingStones = new List<ServiceStone>();
        private static string StaffId;
        public ActionResult TestingExport()
        {
            ViewBag.CurrentUser = CurrentUser.UserID;
            ViewBag.CurrentDate = DateTime.Now.Date.ToShortDateString();
            ViewBag.Workers = this.db.EMPLOYEEs.ToList();

            return View(TestingStones);
        }

        //[HttpPost]
        //public ActionResult TestingExport(FormCollection fc)
        //{
        //    ViewBag.CurrentUser = CurrentUser.UserID;
        //    ViewBag.CurrentDate = DateTime.Now.Date.ToShortDateString();

        //    string id = fc["txtId"];
        //    string weight = fc["txtWeight"];
        //    string quantity = fc["txtQuantity"];
        //    string staffId = fc["txtStaffId"];

        //    if (String.IsNullOrEmpty(staffId) == false)
        //    {
        //        List<STONE_EXPORTSTAFFDETAIL> listSesd = new List<STONE_EXPORTSTAFFDETAIL>();
        //        foreach (var item in TestingStones)
        //        {
        //            STONE_EXPORTSTAFFDETAIL sesd = new STONE_EXPORTSTAFFDETAIL();
        //            sesd.IdStone = item.Id;
        //            sesd.Weight = item.Weight;
        //            sesd.Numb = item.Quantity;
        //            listSesd.Add(sesd);
        //        }

        //        StoneBO.ExportToStaff(staffId, listSesd);

        //        StaffId = "";
        //        ViewBag.StaffId = StaffId;
        //        TestingStones.Clear();

        //        return RedirectToAction("Index");
        //    }
            
        //    return View(TestingStones);
        //}

        public JsonResult SaveTestingExport(int staffId)
        {
            if (staffId != 0)
            {
                STONE_EXPORTSTAFF se = new STONE_EXPORTSTAFF();
                List<STONE_EXPORTSTAFFDETAIL> listSesd = new List<STONE_EXPORTSTAFFDETAIL>();
                foreach (var item in TestingStones)
                {
                    STONE_EXPORTSTAFFDETAIL sesd = new STONE_EXPORTSTAFFDETAIL();
                    sesd.IdStone = item.Id;
                    sesd.Weight = item.Weight;
                    sesd.Numb = item.Quantity;
                    sesd.ReturnWeight = 0;
                    sesd.ReturnQuantity = 0;
                    sesd.Reason = item.Reason;
                    listSesd.Add(sesd);
                }

                StoneBO.ExportToStaff(staffId, se, listSesd);

                StaffId = "";
                ViewBag.StaffId = StaffId;
                TestingStones.Clear();

                return Json(new { result = true, id = se.IdExport }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { result = false, id = -1 }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region Bag Export
        private static List<ServiceStone> BagStones = new List<ServiceStone>();
        public ActionResult BagExport()
        {
            BagStones = new List<ServiceStone>();
            ViewBag.CurrentUser = CurrentUser.UserID;
            ViewBag.CurrentDate = DateTime.Now.Date.ToShortDateString();
            CurrentBagId = "";
            ReceiverId = 0;
            ViewBag.Workers = this.db.EMPLOYEEs.ToList();

            return View(BagStones);
        }

        private static List<BAG_STONE> StonesInBag = new List<BAG_STONE>();
        private static string CurrentBagId;
        private static int ReceiverId;
        
        [HttpPost]
        public ActionResult BagExport(FormCollection fc)
        {
            ViewBag.CurrentUser = CurrentUser.UserID;
            ViewBag.CurrentDate = DateTime.Now.Date.ToShortDateString();
            ViewBag.Workers = this.db.EMPLOYEEs.ToList();

            string id = fc["txtId"];
            string weight = fc["txtWeight"];
            string quantity = fc["txtQuantity"];
            string bagId = fc["txtSearchBagId"];
            int receiver;
            if (Int32.TryParse(fc["receiver"], out receiver) == false)
            {
                receiver = 0;
            }

            if (fc["submit"] == "SEARCH")
            {
                BAG b = db.BAGs.Find(bagId);
                if (b != null)
                {
                    ///*Sang modified*/
                    ///*This is new logic*/
                    ///*Started bag is allowed to export stone*/
                    //if (b.Finish == 0) // mean  this bag is starting
                    //{
                    //    /*Only bag in "Stone Service" process is allowed to export stone*/
                    //    foreach (var bag_process_history in b.BAG_PROCESS_HISTORY)
                    //    {
                    //        if (bag_process_history.Status == 0 //// starting
                    //           && ProcessBO.IsAllowedStoneExport(bag_process_history.IdProcess))
                    //        {
                    //            CurrentBagId = bagId;
                    //            StonesInBag = StoneBO.BagStones(bagId);
                    //            ViewBag.StonesInBag = StonesInBag;
                    //            ViewBag.CurrentBagId = CurrentBagId;
                    //        }
                    //        else
                    //        {
                    //            // Quy part
                    //            // Notice error to View.
                    //            // Message: "This bag is not started or not in process that allowed export stone"
                    //        }
                    //    }
                    //}
                    ///*End Sang modified*/

                    /*Quy Old*/
                    CurrentBagId = bagId;
                    StonesInBag = StoneBO.BagStones(bagId);
                    ViewBag.StonesInBag = StonesInBag;
                    ViewBag.CurrentBagId = CurrentBagId;
                    /*End Quy Old*/
                }
            }
            else if (fc["submit"] == "FINISH")
            {
                //if (String.IsNullOrEmpty(CurrentBagId) == false)
                //{
                //    STONE_EXPORTBAG se = new STONE_EXPORTBAG();
                //    List<BAG_STONE> listSeb = new List<BAG_STONE>();
                //    foreach (var item in BagStones)
                //    {
                //        BAG_STONE bs = new BAG_STONE();
                //        bs.IdStone = item.Id;
                //        bs.Weight = item.Weight;
                //        bs.Numb = item.Quantity;
                //        listSeb.Add(bs);
                //    }

                //    StoneBO.ExportToBag(CurrentBagId, se, listSeb);

                //    BagStones.Clear();
                //    StonesInBag.Clear();
                //    CurrentBagId = "";

                //    return RedirectToAction("Index");
                //}
            }

            ReceiverId = receiver;

            ViewBag.StonesInBag = StonesInBag;
            ViewBag.CurrentBagId = CurrentBagId;
            ViewBag.Receiver = ReceiverId;

            return View(BagStones);
        }

        public JsonResult SaveBagExport(int receiver)
        {
            if (String.IsNullOrEmpty(CurrentBagId) == false && receiver != 0)
            {
                STONE_EXPORTBAG se = new STONE_EXPORTBAG();
                List<BAG_STONE> listSeb = new List<BAG_STONE>();
                foreach (var item in BagStones)
                {
                    BAG_STONE bs = new BAG_STONE();
                    bs.IdStone = item.Id;
                    bs.Weight = item.Weight;
                    bs.Numb = item.Quantity;
                    listSeb.Add(bs);
                }

                // Sang modified
                bool isSuccess = StoneBO.ExportToBag(CurrentBagId, receiver, se, listSeb, BagStones);
                if (isSuccess)
                {
                    BagStones.Clear();
                    StonesInBag.Clear();
                    CurrentBagId = "";
                    return Json(new { result = true, id = se.IdExport }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(new { result = false, id = -1 }, JsonRequestBehavior.AllowGet);
                }

                // Quy old
                //StoneBO.ExportToBag(CurrentBagId, receiver, se, listSeb);
                //BagStones.Clear();
                //StonesInBag.Clear();
                //CurrentBagId = "";
                //return Json(new { result = true, id = se.IdExport }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { result = false, id = -1 }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region History
        private static string id;
        private static DateTime? makedDateFrom;
        private static DateTime? makedDateTo;
        private static bool importBool = true;
        private static bool exportToStaffBool = true;
        private static bool exportToBagBool = true;
        public ActionResult History()
        {
            ViewBag.Id = id;
            ViewBag.MakedDateFrom = makedDateFrom == null ? null : makedDateFrom.Value.ToString("yyyy-MM-dd");
            ViewBag.MakedDateTo = makedDateTo == null ? null : makedDateTo.Value.ToString("yyyy-MM-dd");
            ViewBag.ImportBool = importBool;
            ViewBag.ExportToStaffBool = exportToStaffBool;
            ViewBag.ExportToBagBool = exportToBagBool;

            return View(StoneBO.History(id, makedDateFrom, makedDateTo, Convert.ToBoolean(importBool), Convert.ToBoolean(exportToBagBool), Convert.ToBoolean(exportToStaffBool)));
        }

        [HttpPost]
        public ActionResult History(FormCollection fc)
        {
            if (fc["submit"] == "HISTORY")
            {
                id = fc["txtIdStone"];
                string dateFrom = fc["makedDateFrom"];
                string dateTo = fc["makedDateTo"];
                string import = fc["ckboxImport"];
                string exportToStaff = fc["ckboxExportToStaff"];
                string exportToBag = fc["ckboxExportToBag"];

                makedDateFrom = null;
                if (String.IsNullOrEmpty(dateFrom) == false)
                {
                    makedDateFrom = Convert.ToDateTime(dateFrom);
                }
                makedDateTo = null;
                if (String.IsNullOrEmpty(dateTo) == false)
                {
                    makedDateTo = Convert.ToDateTime(dateTo);
                }

                bool tmp;
                importBool = false;
                exportToStaffBool = false;
                exportToBagBool = false;
                
                if (Boolean.TryParse(import, out tmp) == false)
                {
                    importBool = true;
                }
                if (Boolean.TryParse(exportToStaff, out tmp) == false)
                {
                    exportToStaffBool = true;
                }
                if (Boolean.TryParse(exportToBag, out tmp) == false)
                {
                    exportToBagBool = true;
                }
            }
            else if (fc["submit"] == "CLEAR")
            {
                ClearSearchHistory();
            }

            ViewBag.Id = id;
            ViewBag.MakedDateFrom = makedDateFrom == null ? null : makedDateFrom.Value.ToString("yyyy-MM-dd");
            ViewBag.MakedDateTo = makedDateTo == null ? null : makedDateTo.Value.ToString("yyyy-MM-dd");
            ViewBag.ImportBool = importBool;
            ViewBag.ExportToStaffBool = exportToStaffBool;
            ViewBag.ExportToBagBool = exportToBagBool;

            return View(StoneBO.History(id, makedDateFrom, makedDateTo, Convert.ToBoolean(importBool), Convert.ToBoolean(exportToBagBool), Convert.ToBoolean(exportToStaffBool)));
        }

        private void ClearSearchHistory()
        {
            id = "";
            makedDateFrom = null;
            makedDateTo = null;
            importBool = true;
            exportToBagBool = true;
            exportToStaffBool = true;
        }
        #endregion

        #region Json
        public JsonResult GetStoneInBag(string bagId, string stoneId)
        {
            bool result = true;

            if (bagId == null || stoneId == null)
            {
                result = false;
                return Json(new { result }, JsonRequestBehavior.AllowGet);
            }

            var query = (from d in db.BAG_STONE
                        where d.IdBag == bagId && d.IdStone == stoneId
                        select d).FirstOrDefault();

            if (query == null)
            {
                result = false;
                return Json(new { result }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { result, weight = query.TotalWeight - query.Weight, quantity = query.TotalQty - query.Numb }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SaveToDb(List<StoneViewModel> stones)
        {
            bool result = true;

            foreach (var item in stones)
            {
                STONE stone = new STONE();
                stone.Id = item.Id;
                stone.Name = item.Name;
                stone.Decription = item.Description;
                int x = db.TYPEs.Where(m => m.Name == item.Type).Select(m => m.Id).FirstOrDefault();
                if (x == 0)
                {
                    stone.IdType = null;
                }
                else
                {
                    stone.IdType = x;
                }
                stone.IdUnit = db.UNITs.Where(m => m.Name == item.Unit).Select(m => m.Id).FirstOrDefault();
                stone.Weight = item.Weight;
                stone.Numb = item.Quantity;
                stone.DayMake = DateTime.Now;
                stone.IdCreater = CurrentUser.UserID;

                StoneBO.Add(stone);
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetTypes(string query = null)
        {
            var result = from d in db.TYPEs
                         where d.Name.Contains(query)
                         select new { d.Id, d.Name };
            var s = result.ToList();
            return Json(result.ToList(), JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetUnits(string query = null)
        {
            var result = from d in db.UNITs
                         where d.Name.Contains(query)
                         select new { d.Id, d.Name };
            var s = result.ToList();
            return Json(result.ToList(), JsonRequestBehavior.AllowGet);
        }

        public JsonResult IsTypeNameExisted(string typeName)
        {
            bool result;

            var query = (from d in db.TYPEs
                         where d.Name == typeName
                         select d).FirstOrDefault();

            if (query == null)
            {
                result = false;
            }
            else
            {
                result = true;
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult IsUnitNameExisted(string unitName)
        {
            bool result;

            var query = (from d in db.UNITs
                         where d.Name == unitName
                         select d).FirstOrDefault();

            if (query == null)
            {
                result = false;
            }
            else
            {
                result = true;
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult ClearImportForm()
        {
            bool result = true;

            ImportedStones.Clear();

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult ClearTestingExportForm()
        {
            bool result = true;

            TestingStones.Clear();
            StaffId = "";

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult ClearBagExportForm()
        {
            bool result = true;

            BagStones.Clear();
            StonesInBag.Clear();
            CurrentBagId = "";

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult IsStoneExisted(string id)
        {
            bool result;

            STONE p = db.STONEs.Find(id);
            if (p == null)
            {
                result = false;
            }
            else
            {
                result = true;
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult IsStoneExistedInBag(string bagId, string stoneId)
        {
            bool result = true;

            if (bagId == null || stoneId == null)
            {
                result = false;
                return Json(new { result }, JsonRequestBehavior.AllowGet);
            }

            var query = (from d in db.BAG_STONE
                         where d.IdBag == bagId && d.IdStone == stoneId
                         select d).FirstOrDefault();

            if (query == null)
            {
                result = false;
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult AddImport(string id, float weight, int quantity, string reason)
        {
            bool result = true;

            ImportedStones.Add(new ServiceStone() { Id = id, Weight = weight, Quantity = quantity, Reason = reason });

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult AddTestingExport(string id, float weight, int quantity, string reason)
        {
            bool result = true;

            TestingStones.Add(new ServiceStone() { Id = id, Weight = weight, Quantity = quantity, Reason = reason });

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult AddBagExport(string bagId, string stoneId, float weightIn, int quantityIn, string reason)
        {
            bool result = true;

            if (bagId == null || stoneId == null)
            {
                result = false;
                return Json(new { result }, JsonRequestBehavior.AllowGet);
            }

            var query = (from d in db.BAG_STONE
                         where d.IdBag == bagId && d.IdStone == stoneId
                         select d).FirstOrDefault();

            if (query == null)
            {
                result = false;
                return Json(new { result }, JsonRequestBehavior.AllowGet);
            }

            BagStones.Add(new ServiceStone() { Id = stoneId, Weight = weightIn, Quantity = quantityIn, Reason = reason });
            
            return Json(new { result, weight = query.TotalWeight - query.Weight, quantity = query.TotalQty - query.Numb }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetStones(string query = null)
        {
            var result = from d in db.STONEs
                         where d.Id.Contains(query)
                         select d.Id;
            var s = result.ToList();
            return Json(result.ToList(), JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetStoneNames(string query = null)
        {
            var result = from d in db.STONEs
                         where d.Name.Contains(query)
                         select d.Name;
            
            return Json(result.Distinct().ToList(), JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetBagIds(string query = null)
        {
            /*Quy old*/
            //var result = from d in db.BAGs
            //             where d.Id.Contains(query)
            //             select d.Id;

            /*Sang new*/
            var bag_ids = (from d in db.BAGs
                          where d.Finish == 0 && d.Id.Contains(query)
                          select d.Id).ToList();
            for (int index_bag = 0; index_bag < bag_ids.Count; index_bag++)
            {
                if (!ProcessBO.IsAllowedStoneExport(MCBagBO.GetCurrentProcessId(bag_ids[index_bag])))
                {
                    bag_ids.Remove(bag_ids[index_bag]);
                    --index_bag;
                }
            }
            return Json(bag_ids, JsonRequestBehavior.AllowGet);
        }

        public JsonResult Update(string id, string name, string description)
        {
            bool result = true;

            STONE s = new STONE() { Id = id, Name = name, Decription = description };
            StoneBO.Update(s);

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult Delete(string id)
        {
            bool result = true;

            StoneBO.Delete(id);

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult UpdateImportStone(string id, double weight, int quantity, string reason)
        {
            bool result = true;

            ServiceStone s = ImportedStones.Where(m => m.Id == id).FirstOrDefault();
            if (s == null)
                result = false;
            else
            {
                s.Weight = weight;
                s.Quantity = quantity;
                s.Reason = reason;
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DeleteImportStone(string id)
        {
            bool result = true;

            ServiceStone s = ImportedStones.Where(m => m.Id == id).FirstOrDefault();
            if (s == null)
                result = false;
            else
                ImportedStones.Remove(s);

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult UpdateTestingExportStone(string id, double weight, int quantity, string reason)
        {
            bool result = true;

            ServiceStone s = TestingStones.Where(m => m.Id == id).FirstOrDefault();
            if (s == null)
                result = false;
            else
            {
                s.Weight = weight;
                s.Quantity = quantity;
                s.Reason = reason;
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DeleteTestingExportStone(string id)
        {
            bool result = true;

            ServiceStone s = TestingStones.Where(m => m.Id == id).FirstOrDefault();
            if (s == null)
                result = false;
            else
                TestingStones.Remove(s);

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult UpdateBagExportStone(string id, double weight, int quantity, string reason)
        {
            bool result = true;

            ServiceStone s = BagStones.Where(m => m.Id == id).FirstOrDefault();
            if (s == null)
                result = false;
            else
            {
                s.Weight = weight;
                s.Quantity = quantity;
                s.Reason = reason;
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DeleteBagExportStone(string id)
        {
            bool result = true;

            ServiceStone s = BagStones.Where(m => m.Id == id).FirstOrDefault();
            if (s == null)
                result = false;
            else
                BagStones.Remove(s);

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}